package org.i_plus.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.i_plus.model.MapBean;
import org.i_plus.model.services.MapService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Servlet implementation class GiftServlet
 */
@WebServlet("/MapServlet")
@MultipartConfig
public class MapServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private MapService service;

	public void init() throws ServletException {
		WebApplicationContext context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		this.service = (MapService) context.getBean("mapService");
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");

		String id = request.getParameter("id");

		if (id != null) {
			// service 呼叫它的方法，回傳 (尋找單一篇文章) 之後設定屬性，派導給 Map.jsp
			MapBean map = service.selectByPK(Integer.parseInt(id));

			Map<String, String> result = new HashMap<String,String>();
			result.put("account", map.getAccount());
			result.put("m_num", Integer.toString(map.getM_num()));
			result.put("m_content", map.getM_content());
			result.put("x_axis", Double.toString(map.getX_axis()));
			result.put("y_axis", Double.toString(map.getY_axis()));
			result.put("m_title", map.getM_title());
	
			request.setAttribute("map", result);
			request.getRequestDispatcher("/View/Map.jsp").forward(request,
					response);
			return;
		} else {
			// service 呼叫它的方法 ，搜尋所有文章，回傳 List<MapBean> ，派導給 Maps.jsp
			List<MapBean> maps = service.selectAll();// 先抓取所有的MAP文章資料
			List<String[]> result = new ArrayList<String[]>();//為了重新放轉成base64的圖片
			for(MapBean temp :maps){
				String str = temp.getM_content();
				if(str.length()>10)
					str = str.substring(0, 10);
				String map[] = {temp.getAccount(),Integer.toString(temp.getM_num()),
						str,Double.toString(temp.getX_axis()),
						Double.toString(temp.getY_axis()),temp.getM_title()
				};
				//account;m_num;m_content;x_axis;y_axis;m_title;m_pic;
				result.add(map);
			}			
			request.setAttribute("maps", result);			
			request.getRequestDispatcher("/View/Maps.jsp").forward(request,
					response);
			return;
		}
		
	}
}
